package com.datang.pet.api.petController;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-06-21 18:39
 * @notify
 * @version 1.0
 */

import com.datang.pet.common.redis.RedisTool;
import com.datang.pet.common.response.Result;
import com.datang.pet.common.utils.MD5;
import com.datang.pet.common.utils.StringUtils;
import com.datang.pet.pojo.Pet;
import com.datang.pet.service.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
public class GetAllPetByUserIdController {

    @Autowired
    private PetService petService;

    @Autowired
    private RedisTool redisTool;

    @GetMapping("/getAllPetByUserId")
    public Result getAllPetByUserId(String userId) throws Exception {
        if (!StringUtils.isNUll(userId)) {
            throw new Exception("用户id为空");
        }
        try {
            userId = (MD5.decryptData(userId));
        } catch (Exception e) {
            throw new Exception("userId解密出错！");
        }


        List<Pet> list = (List) redisTool.get("getAllPetByUserId" + userId);
        if (list == null) {
            list = petService.getAllPetByUserId(userId);
            redisTool.set("getAllPetByUserId" + userId, list);
        }


        //当前时间
        Date nowTime = new Date();
        for (Pet p : list) {
            Long i = (nowTime.getTime() - p.getBirthday().getTime())/(1000*60 * 60 * 24);
            if(i==0L){
                i=1L;
            }
            p.setShowDay(i);
        }

        return Result.ok(list);
    }

}
